package com.zznzzn.myweb.interceptor;

import com.zznzzn.myweb.util.JWTUtil;
import org.springframework.http.HttpMethod;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JWTInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//        System.out.println("================="+request.getMethod());

        //放行options请求
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        // 获取请求头信息authorization信息
        final String authHeader = request.getHeader(JWTUtil.AUTH_HEADER_KEY);

        if (StringUtils.isEmpty(authHeader)) {
            String contextPath = request.getContextPath();
            response.sendRedirect(contextPath+"/error?error=401");
            return false;
        }else{
            return true;
        }


        //只检查是否带token，不做合法性检查


    }
}
